<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    // post请求
    function xhr_post() {
        let xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://www.liulongbin.top:3006/api/addbook');
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send('bookname=测试测试测试测&author=测试test01&publisher=测试test01');
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let res = xhr.responseText;
                console.log(res);
            }
        }
    }

    // get请求
    function xhr_get() {
        let xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks');
        xhr.send();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let res = xhr.responseText;
                console.log(res);
            }
        }
    }
    // xhr_get();

    // FormData
    function xhr_formData() {
        let fd = new FormData();
        fd.append('uname', 'ls');
        fd.append('upwd', '123456');
        console.log(fd, typeof fd, fd instanceof FormData);
        let xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://www.liulongbin.top:3006/api/formdata');
        xhr.send(fd);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let res = JSON.parse(xhr.responseText);
                console.log(res);
            }
        }
    }

    // 简单封装
    // 简单封装
    const ajax = options => {
        options = Object.assign({
            method: 'GET',
            data: {},
            timeout: 3000,
        }, options);
        const queryStr = obj => Object.keys(obj || {}).reduce((p, n) => p.concat(`${n}=${obj[n]}`), []).join('&');
        const xhr = new XMLHttpRequest();
        Object.keys(options).forEach(el => el !== 'method' && el !== 'data' && (xhr.el = options[el]));
        let data = options.data;
        if (typeof options.data == 'function') {
            data = options.data();
        }
        if (options.method.toUpperCase() === 'POST') {
            xhr.open(options.method, options.url);
            !(data instanceof FormData) && xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send(data instanceof FormData ? data : queryStr(data));
        }
        if (options.method.toUpperCase() === 'GET') {
            let qs = queryStr(data);
            xhr.open(options.method, qs ? options.url + (options.url.indexOf('?') === -1 ? '?' : '&') + qs : options.url);
            xhr.send();
        }
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let res = xhr.responseType == 'json' ? xhr.responseText : JSON.parse(xhr.responseText);
                'function' === typeof options.success && options.success(res);
            }
        }
        xhr.ontimeout = function () {
            'function' === typeof options.timeout && options.timeout(new Error('请求超时'));
        }
        xhr.onerror = function () {
            'function' === typeof options.error && options.error(xhr.statusText);
        }
    }

    // 获取
    ajax({
        method: 'GET',
        url: 'http://www.liulongbin.top:3006/api/getbooks',
        success: function (res) {
            console.log(res);
        },
        timeout: function (err) {
            console.log(err);
        },
        error(err) {
            console.log(err);
        }
    });

    // 表单
    ajax({
        method: 'POST',
        url: 'http://www.liulongbin.top:3006/api/formdata',
        data: function () {
            let fd = new FormData();
            fd.append('uname', 'ls');
            fd.append('upwd', '123456');
            return fd;
        },
        success: function (res) {
            console.log(res);
        },
        error(err) {
            console.log(err);
        }
    });

    // 添加
    ajax({
        method: 'POST',
        url: 'http://www.liulongbin.top:3006/api/addbook',
        data: {
            bookname: '测试测试测试试',
            author: '测试test01',
            publisher: '测试test01'
        },
        success: function (res) {
            console.log(res);
        }
    });

</script>

</html>